﻿using System;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.UI;
using Grundy.Administration.Web.Models;
using Grundy.Administration.Web.Services;
using Grundy.Common;
using Grundy.Entity;
using Grundy.Message;

namespace Grundy.Administration.Web.Controllers
{
    [Authorize]
    public class LicenseController : Controller
    {
        private LicenseService _licenseService;
        private FeatureService _featureService;

        public LicenseController()
        {
            _licenseService = new LicenseService();
            _featureService = new FeatureService(_licenseService.Db);
        }

        public LicenseController(LicenseService licenseService, FeatureService featureService)
        {
            _licenseService = licenseService;
            _featureService = featureService;
        }

        [HttpPost]
        public ActionResult GetLicensesData(int page = 1, int rows = 0)
        {
            var totalRecords = _licenseService.GetLicenses().Count();
            var licenses = _licenseService.GetLicenses(page, rows)
                           .ToList();

            var data = new
            {
                total = page,
                page = page,
                records = totalRecords,
                rows = licenses.Select((i) => new { Id = i.Id, cell = new object[] { i.Id, i.Name, GetSummary(i)} }).ToList()
            };

            return Json(data);
        }

        private string GetSummary(License license)
        {
            var sb = new StringBuilder("<strong>{0}</strong> license. ".FormatWith(license.Type));
            if (license is FloatingLicense)
            {
                var fl = (FloatingLicense)license;
                sb = sb.AppendFormat(" Each {0} session is counted. ", fl.Client);
                if (fl is CountedFloatingLicense)
                {
                    var cl = (CountedFloatingLicense) fl;
                    sb = sb.AppendFormat("{0} {1} are available.", cl.Limit, cl.LimitType == FloatingLicenseLimitType.Execution ? "executions" : "concurrent connections");
                }
            }
            return sb.ToString();
        }

        public ActionResult GetLicenses()
        {
            var totalRecords = _licenseService.GetLicenses().Count();
            ViewBag.IsEmpty = totalRecords == 0;
            return View();
        }

        [HttpPost]
        public ActionResult New(LicenseViewModel licenseViewModel)
        {
            var license = _licenseService.GetLicense(licenseViewModel.Name);
            if (license == null)
            {
                var createdLicense = licenseViewModel.ToLicense(_featureService);
                if (!createdLicense.Item1)
                {
                    return Json(new object[] { false, createdLicense.Item2, Guid.Empty });
                }
                var created = _licenseService.CreateLicense(createdLicense.Item3);
                return Json(new object[] { true, string.Empty, created.Id });
            }
            return Json(new object[] { false, "A license with the same name already exists.", Guid.Empty });
        }

        public ActionResult SearchLicenses(string term)
        {   
            if (term.IsNullOrEmpty() || term.Length < 2)
                return Json(new object[] { }, JsonRequestBehavior.AllowGet);

            var matching = _licenseService.GetLicenses().Where(i => i.Name.StartsWith(term))
                           .Select(i => i.Name)
                           .ToList();
            return Json(matching, JsonRequestBehavior.AllowGet);
        }
    }
}